//
//  SYPhotoBrowserCell.swift
//  SingWeibo
//
//  Created by shiying on 15/12/31.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit

import SDWebImage

import SVProgressHUD

import FLAnimatedImage

let ImageMinimumZoomScale: CGFloat = 0.5

let dismissZoomScale: CGFloat = 0.75
class SYPhotoBrowserCell: UICollectionViewCell {
    var cellDelegate: SYPhotoBrowserCellDelegate?
    
    var imageURL: NSURL? {
        didSet {
        
            imageView.image = nil // 为了防止重用，要在赋值先清空
            
            
            let path = SDWebImageManager.sharedManager().imageCache.defaultCachePathForKey(imageURL!.absoluteString)
            let data = NSData(contentsOfFile: path)
            
            if data != nil {
                // 表示之前有缓存
                let image = UIImage(data: data!)!
                self.setImage(image, data: data!)
                return
            }
            
            // 下载图片并显示
            SDWebImageDownloader.sharedDownloader().downloadImageWithURL(imageURL, options: SDWebImageDownloaderOptions(rawValue: 0), progress: { (receive, total) -> Void in
                // 获取进度
                let progress = Float(receive) / Float(total)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    SVProgressHUD.showProgress(progress)
                })
                }) { (image, data, error, finished) -> Void in
                    SDWebImageManager.sharedManager().imageCache.storeImage(image, recalculateFromImage: false, imageData: data, forKey: self.imageURL!.absoluteString, toDisk: true)
                    // 回去主线程显示图片
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.setImage(image, data: data)
                    })
            }
        }
    }
    
    private func setImage(image: UIImage, data: NSData) {
        let gif = self.imageURL!.absoluteString.lowercaseString.hasSuffix("gif")
        
        if !gif {
        
            self.imageView.image = image
        } else {
            // 创建gifImage
            let animatedImage = FLAnimatedImage(animatedGIFData: data)
            self.imageView.animatedImage = animatedImage
            
        }
        SVProgressHUD.dismiss()
    
        // 修改imageView的大小
        self.layouImageView(image)
    }
   
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func layouImageView(image: UIImage) {
    
        let imageSize = displaySize(image) // 获取一张图片的大小
        
        if imageSize.height < UIScreen.mainScreen().bounds.height {
            // 短图居中显示
            imageView.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
            let offsetY = (UIScreen.mainScreen().bounds.height - imageSize.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
        
        } else {
            // 长图
            imageView.frame = CGRect(origin: CGPointZero, size: imageSize)
            scrollView.contentSize = imageSize // 设置可以让图片滚动
        }
    }
    
    // 返回一张图片的大小
    func displaySize(image: UIImage) -> CGSize {
        let newWidth = UIScreen.mainScreen().bounds.width // 图片的宽就是全宽
        
        let newHeight = newWidth * image.size.height / image.size.width // 获得图片的高
        
        return CGSize(width: newWidth, height: newHeight) // 返回大小
    }
    
    
    /// 准备UI
    func prepareUI() {
        
        scrollView.delegate = self
        scrollView.maximumZoomScale = 2
        scrollView.minimumZoomScale = ImageMinimumZoomScale
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(activityIndicator)
        
        
        
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView]))
        
        contentView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
    }
    
    
    // MARK: - 懒加载
    private lazy var scrollView: UIScrollView = UIScrollView()
    
    lazy var imageView: SYImageView = SYImageView()
    
    // 菊花
    private lazy var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}

// MARK: - SYPhotoBrowserCellDelegate 代理方法
protocol SYPhotoBrowserCellDelegate: NSObjectProtocol {

    // 获取代理（控制器）的背景
    func viewForTransparent() -> UIView
    
    // 通知控制器关闭
    func cellForDissmissController()
    
    // 获取缩略图的位置
    func targetRectForDismissController() -> CGRect

}


extension SYPhotoBrowserCell: UIScrollViewDelegate {

    // 告诉ScrollView要缩放哪个View
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        // 修改控制器的背景透明度
        let backGroundView = cellDelegate?.viewForTransparent()
        
        let alpha = imageView.transform.a * 0.7 + 0.2
        
        //设置alpha
        if alpha < 1 {
            backGroundView?.alpha = alpha
        } else {
            backGroundView?.alpha = 1
        }
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        if scale < dismissZoomScale { // 如果缩放比例小于指定的比例直接关闭控制器
            
            if let newFrame = cellDelegate?.targetRectForDismissController() {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.imageView.contentMode = UIViewContentMode.ScaleAspectFill
                    self.imageView.clipsToBounds = true
                    
                    //移动到新位置
                    self.imageView.frame = CGRect(origin: CGPointZero, size: newFrame.size)
                    // 顶部和左边需要的间距
                    scrollView.contentInset = UIEdgeInsets(top: newFrame.origin.y, left: newFrame.origin.x, bottom: 0, right: 0)
                    
                    // 当图片是长图的时候就会发现origin.y的值是不对的
                    scrollView.contentOffset.x = -newFrame.origin.x
                    scrollView.contentOffset.y = -newFrame.origin.y
                    },completion: {(_) -> Void in
                        self.cellDelegate?.cellForDissmissController()
                })
            }
        } else {
            var offsetX = (scrollView.bounds.width - imageView.frame.width) * 0.5
            var offsetY = (scrollView.bounds.height - imageView.frame.height) * 0.5
            
            offsetX = offsetX < 0 ? 0 : offsetX
            offsetY = offsetY < 0 ? 0 : offsetY
            
            UIView.animateWithDuration(0.25) { () -> Void in
                scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
            }
        }
    }
}
